from django.shortcuts import render,HttpResponse
from myblog.models import Article,ClassIfication,ArticleTags
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.

def page(request,data):
	'''分页方法'''
	limit = 8  # 设置每页的数量
	paginator = Paginator(data, limit)  # 实例化一个分页对象
	page = request.GET.get('page')  # 获取页码
	try:
		articles = paginator.page(page)  # 获取某页对应的记录
	except PageNotAnInteger:  # 如果页码不是个整数
		articles = paginator.page(1)  # 取第一页的记录
	except EmptyPage:  # 如果页码太大，没有相应的记录
		articles = paginator.page(paginator.num_pages)  # 取最后一页的记录
	return articles

def index(request):
	article = Article.objects.all()  #所有文章
	classification = ClassIfication.objects.all()  #分类
	articletags = ArticleTags.objects.all()   #标签
	articles = page(request,article)
	return render(request,'index.html',{'article':articles,'classification':classification,'articletags':articletags})

def classpage(request,classid):
	classification = ClassIfication.objects.all()  #分类
	articletags = ArticleTags.objects.all()   #标签
	if request.method == 'GET':
		article = Article.objects.filter(classification_id=classid).all()
		articles = page(request, article)
		return render(request, 'classpage.html',{'article': articles, 'classification': classification, 'articletags': articletags,'classid':classid})


def detailed(request,articleid):
	classification = ClassIfication.objects.all()  #分类
	articletags = ArticleTags.objects.all()   #标签
	if request.method == 'GET':
		try:
			article = Article.objects.filter(id=articleid)
		except:
			return HttpResponse('文章不存在')

		return render(request, 'detailed.html',{'article': article, 'classification': classification, 'articletags': articletags})